/**
 * 数据导出页面 - 多格式导出、报表生成
 * 支持：PDF、Word、Excel、图片导出
 */
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Download, FileText, FileSpreadsheet, File, Image, Eye, RefreshCw, Settings, CheckSquare, Square } from 'lucide-react';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
import { Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell, WidthType, AlignmentType } from 'docx';
import { dashboardAPI, type SalesTrendItem, type CategorySalesItem, type OrderDetailItem, type DataComparisonItem, type RealTimeData } from '../../utils/api';

interface ExportConfig {
  dataTypes: string[];
  dateRange: string;
  format: 'pdf' | 'excel' | 'word' | 'image';
  template: 'report' | 'contract' | 'list';
  includeCharts: boolean;
  includeSummary: boolean;
}

interface ExportPreset {
  id: string;
  name: string;
  description: string;
  config: {
    dataTypes: string[];
    dateRange: string;
    format: 'pdf' | 'excel' | 'word' | 'image';
  };
}

// 订单数据类型，与Dashboard.tsx保持一致
interface ProductInfo {
  _id: string;
  shopname: string;
  price: number;
  nums: number;
  store: string;
}

interface OrderData {
  _id: string;
  studentId: ProductInfo;
  quantity: number;
  totalPrice: string;
  customerName: string;
  customerPhone: string;
  address: string;
  status: '待处理' | '已发货' | '已完成' | '已取消';
  createdAt: string;
}

// 商品数据接口
interface ProductData {
  _id: string;
  shopname: string;
  store: string;
  pass: string;
  price: string;
  nums: number;
  tid: string;
}

type OrderColumnKey = 'product' | 'user' | 'region' | 'amount' | 'time';

interface ExportHistoryItem {
  id: string;
  time: string;
  types: string;
  format: string;
  status: '成功' | '失败';
  message?: string;
  config: {
    dataTypes: string[];
    dateRange: string;
    format: 'pdf' | 'excel' | 'word' | 'image';
    orderColumns: OrderColumnKey[];
  };
}

// 解析订单价格（支持字符串和数字）- 移到组件外部以避免依赖项变化
const parsePrice = (price: string | number): number => {
  if (typeof price === 'number') return price;
  if (typeof price === 'string') {
    const cleanPrice = price.replace(/[¥\s,]/g, '').trim();
    return parseFloat(cleanPrice) || 0;
  }
  return 0;
};

const createMockRealTimeData = (productCount: number): RealTimeData => ({
  sales: 4325000,
  orders: 4532,
  users: 12580,
  products: productCount || 568,
  conversionRate: 3.8,
  avgOrderValue: 954,
  stockAlerts: 23,
  returnRate: 2.3,
  salesTrend: 15.8,
  ordersTrend: 8.2
});

const DataExport: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const previewRef = useRef<HTMLDivElement>(null);
  const productsRef = useRef<ProductData[]>([]);
  const [exportConfig, setExportConfig] = useState<ExportConfig>({
    dataTypes: ['sales', 'orders'],
    dateRange: '30',
    format: 'pdf',
    template: 'report',
    includeCharts: true,
    includeSummary: true
  });

  const exportPresets: ExportPreset[] = [
    {
      id: 'weekly-ops',
      name: '周运营报表',
      description: '最近7天 · 销售+订单 · Excel',
      config: {
        dataTypes: ['sales', 'orders'],
        dateRange: '7',
        format: 'excel'
      }
    },
    {
      id: 'monthly-business',
      name: '月度经营报表',
      description: '最近30天 · 销售+订单+类别 · Excel',
      config: {
        dataTypes: ['sales', 'orders', 'categories'],
        dateRange: '30',
        format: 'excel'
      }
    },
    {
      id: 'summary-pdf',
      name: '管理层摘要（PDF）',
      description: '最近30天 · 销售+对比+实时 · PDF',
      config: {
        dataTypes: ['sales', 'comparison', 'realtime'],
        dateRange: '30',
        format: 'pdf'
      }
    }
  ];

  const dataTypeOptions = [
    { id: 'sales', label: '销售数据', description: '销售趋势、销售额等' },
    { id: 'orders', label: '订单数据', description: '订单明细、订单统计等' },
    { id: 'categories', label: '类别数据', description: '商品类别销售数据' },
    { id: 'comparison', label: '对比数据', description: '数据对比分析' },
    { id: 'realtime', label: '实时数据', description: '实时业务指标' }
  ];

  const orderColumnOptions: { id: OrderColumnKey; label: string }[] = [
    { id: 'product', label: '商品' },
    { id: 'user', label: '用户' },
    { id: 'region', label: '地区' },
    { id: 'amount', label: '金额(元)' },
    { id: 'time', label: '时间' }
  ];

  const [exportData, setExportData] = useState<{
    salesTrend?: SalesTrendItem[];
    categorySales?: CategorySalesItem[];
    orders?: OrderDetailItem[];
    comparison?: DataComparisonItem[];
    realtime?: RealTimeData;
  }>({});

  // 导出过程不再在按钮上展示加载状态，仅在后台执行
  const [orderColumns, setOrderColumns] = useState<OrderColumnKey[]>(['product', 'user', 'region', 'amount', 'time']);
  const [exportHistory, setExportHistory] = useState<ExportHistoryItem[]>([]);
  const [confirmVisible, setConfirmVisible] = useState(false);


  // 生成模拟销售数据 - 与Dashboard.tsx保持同步
  const generateMockSalesData = (days: number): SalesTrendItem[] => {
    // 模拟订单数据，与Dashboard.tsx中的逻辑保持一致
    const mockOrders = [];
    const today = new Date();
    
    // 为每天生成随机订单数
    for (let i = days - 1; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(today.getDate() - i);
      
      // 每天生成5-20个随机订单
      const dailyOrderCount = Math.floor(5 + Math.random() * 15);
      
      for (let j = 0; j < dailyOrderCount; j++) {
        // 订单金额范围：5000-50000
        const orderAmount = Math.floor(5000 + Math.random() * 45000);
        mockOrders.push({
          createdAt: date.toISOString(),
          amount: orderAmount
        });
      }
    }
    
    // 创建日期映射，聚合每日销售额和订单数
    const dateMap = new Map<string, { sales: number; orders: number }>();
    
    // 初始化所有日期
    for (let i = days - 1; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(today.getDate() - i);
      const dateKey = date.toISOString().split('T')[0];
      dateMap.set(dateKey, { sales: 0, orders: 0 });
    }
    
    // 聚合订单数据
    mockOrders.forEach(order => {
      const dateKey = order.createdAt.split('T')[0];
      if (dateMap.has(dateKey)) {
        const currentData = dateMap.get(dateKey)!;
        dateMap.set(dateKey, {
          sales: currentData.sales + order.amount,
          orders: currentData.orders + 1
        });
      }
    });
    
    // 转换为所需格式并排序
    const result: SalesTrendItem[] = Array.from(dateMap.entries()).map(([date, data]) => ({
      date,
      sales: data.sales,
      orders: data.orders
    }));
    
    // 按日期升序排序
    return result.sort((a, b) => a.date.localeCompare(b.date));
  };

  // 生成模拟类别销售数据 - 与Dashboard.tsx保持同步
  const generateMockCategoryData = (): CategorySalesItem[] => {
    // 模拟订单数据，与Dashboard.tsx中的类别销售对比图表保持一致
    const mockOrders = [
      { shopname: '拯救者p8000', amount: 140000, count: 4 },
      { shopname: '洗衣机', amount: 50000, count: 3 },
      { shopname: '吹风机', amount: 10000, count: 3 }
    ];
    
    // 使用与Dashboard相同的逻辑计算类别销售数据
    const categoryMap = new Map<string, { sales: number; orders: number }>();
    
    mockOrders.forEach(order => {
      const { shopname, amount, count } = order;
      if (categoryMap.has(shopname)) {
        const existing = categoryMap.get(shopname)!;
        categoryMap.set(shopname, {
          sales: existing.sales + amount,
          orders: existing.orders + count
        });
      } else {
        categoryMap.set(shopname, {
          sales: amount,
          orders: count
        });
      }
    });
    
    // 转换为所需格式并排序
    const result = Array.from(categoryMap.entries()).map(([name, data]) => ({
      name,
      sales: data.sales,
      orders: data.orders
    }));
    
    // 按销售额降序排序
    return result.sort((a, b) => b.sales - a.sales);
  };

  // 生成模拟订单数据
  const generateMockOrderData = (limit: number): OrderDetailItem[] => {
    const products = ['智能手机', '笔记本电脑', '平板电脑', '智能手表', '无线耳机', '相机', '游戏手柄', '移动电源'];
    const regions = ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '南京'];
    const users = ['user_001', 'user_002', 'user_003', 'user_004', 'user_005'];
    
    const data: OrderDetailItem[] = [];
    const today = new Date();
    
    for (let i = 0; i < limit; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() - Math.floor(Math.random() * 30));
      
      data.push({
        id: `order_${String(i + 1).padStart(6, '0')}`,
        product: products[Math.floor(Math.random() * products.length)],
        user: users[Math.floor(Math.random() * users.length)],
        region: regions[Math.floor(Math.random() * regions.length)],
        amount: Math.round(1000 + Math.random() * 9000),
        time: date.toISOString()
      });
    }
    
    return data;
  };
  
  // 从订单数据计算实时销售数据 - 与Dashboard.tsx保持一致
  const calculateRealTimeDataFromOrders = useCallback((orders: OrderData[]) => {
    // 计算今日销售额和订单数
    const today = new Date().toISOString().split('T')[0];
    let todaySales = 0;
    let todayOrders = 0;
    let totalAmount = 0;

    // 统计所有订单的总销售额
    orders.forEach((order: OrderData) => {
      try {
        const price = parsePrice(order.totalPrice);
        totalAmount += price;

        // 检查是否为今日订单
        if (order.createdAt) {
          const orderDate = new Date(order.createdAt).toISOString().split('T')[0];
          if (orderDate === today) {
            todaySales += price;
            todayOrders += 1;
          }
        }
      } catch (e) {
        console.warn('[数据导出] 处理订单数据失败:', order._id, e);
      }
    });

    // 计算客单价
    const avgOrderValue = orders.length > 0 ? Math.round(totalAmount / orders.length) : 0;

    // 设置默认趋势值
    const salesTrend = 15.8;
    const ordersTrend = 8.2;

    return {
      sales: todaySales,
      orders: todayOrders,
      avgOrderValue,
      salesTrend,
      ordersTrend
    };
  }, []); // parsePrice 已移到组件外部，无需依赖
  
  // 获取商品数据 - 与Dashboard.tsx保持一致
  const fetchProducts = useCallback(async () => {
    try {

      const response = await fetch('http://localhost:3000/hsl/product/list', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      const data = await response.json();
      
      if (data.code === 200 && Array.isArray(data.data)) {
        productsRef.current = data.data;
        console.log('[数据导出] 成功获取商品数据:', data.data.length, '件商品');
      }
    } catch (error) {
      console.error('[数据导出] 获取商品数据失败:', error);
    }
  }, []);
  
  // 获取订单数据 - 与Dashboard.tsx保持一致
  const fetchOrdersData = useCallback(async () => {
    try {
      console.log('[数据导出] 开始获取订单数据...');
      const ordersRes = await fetch('http://localhost:3000/hsl/order/list', {
        cache: 'no-cache',
        headers: {
          'Cache-Control': 'no-cache',
          'Pragma': 'no-cache'
        }
      });
      const ordersData = await ordersRes.json();

      if (ordersData.code === 200 && Array.isArray(ordersData.data)) {
        const orders = ordersData.data || [];
        console.log('[数据导出] 成功获取订单数据:', orders.length, '条');
        return orders;
      } else {
        console.warn('[数据导出] API返回格式不符，使用空数组');
        return [];
      }
    } catch (err) {
      console.error('[数据导出] 获取订单列表失败:', err);
      return [];
    }
  }, []);
  
  // 生成模拟实时数据（作为后备）
  // 从数据对比中获取趋势百分比（与Dashboard.tsx保持一致）
  const getTrendFromComparison = useCallback((label: string, comparisonData?: DataComparisonItem[]) => {
    const comparison = comparisonData || exportData.comparison;
    if (!comparison) return null;
    
    const item = comparison.find(c => c.label.includes(label))
    if (item && item.previousValue > 0) {
      const change = ((item.currentValue - item.previousValue) / item.previousValue) * 100
      return {
        value: `${change > 0 ? '+' : ''}${change.toFixed(1)}%`,
        isUp: change > 0
      }
    }
    return null
  }, [exportData.comparison]);

  // 生成模拟对比数据 - 与Dashboard.tsx保持同步
  const generateMockComparisonData = (): DataComparisonItem[] => {
    // 模拟对比数据，与Dashboard.tsx中的销售数据对比分析保持一致
    return [
      {
        metric: 'sales',
        currentValue: 3200000,
        previousValue: 2800000,
        growthRate: 14.3,
        label: '本期销售额',
        previousLabel: '上期销售额',
        unit: '元'
      },
      {
        metric: 'orders',
        currentValue: 4567,
        previousValue: 3890,
        growthRate: 17.4,
        label: '本期订单数',
        previousLabel: '上期订单数',
        unit: '单'
      },
      {
        metric: 'users',
        currentValue: 1234,
        previousValue: 1056,
        growthRate: 16.8,
        label: '新增用户',
        previousLabel: '上期新增',
        unit: '人'
      }
    ];
  };

  // 获取导出数据 - 增强版本，支持自动重试和模拟数据作为后备
  const fetchExportData = useCallback(async () => {
    if (exportConfig.dataTypes.length === 0) return;
    
    try {
      setLoading(true);
      const newData: typeof exportData = {};
      let hasError = false;
      let hasApiError = false;
      const errorMessages: string[] = [];
      const retryLimit = 2;
      let latestOrdersFromBackend: OrderData[] | null = null;

      // 带重试的API请求函数
      const fetchWithRetry = async <T,>(fetchFn: () => Promise<T>, maxRetries: number = retryLimit): Promise<T> => {
        let lastError: unknown = null;
        
        for (let attempt = 0; attempt <= maxRetries; attempt++) {
          try {
            return await fetchFn();
          } catch (error) {
            lastError = error;
            console.warn(`请求失败 (尝试 ${attempt + 1}/${maxRetries + 1}):`, error);
            if (attempt < maxRetries) {
              // 等待一段时间后重试
              await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1)));
            }
          }
        }
        
        throw lastError;
      };

      // 统一解析 API 响应的数据结构
      const extractResponseData = <T,>(response: unknown): T | null => {
        if (!response) return null;

        // 如果本身就是目标数据
        if (Array.isArray(response) || typeof response === 'object' && response !== null && !('data' in (response as Record<string, unknown>))) {
          return response as T;
        }

        if (typeof response === 'object' && response !== null) {
          const respObj = response as Record<string, unknown>;
          const firstLevel = respObj.data;

          if (Array.isArray(firstLevel) || typeof firstLevel === 'object') {
            if (Array.isArray(firstLevel)) {
              return firstLevel as T;
            }

            if (firstLevel && typeof firstLevel === 'object' && 'data' in (firstLevel as Record<string, unknown>)) {
              const secondLevel = (firstLevel as Record<string, unknown>).data;
              if (Array.isArray(secondLevel) || typeof secondLevel === 'object') {
                return secondLevel as T;
              }
            }

            return firstLevel as T;
          }
        }

        return null;
      };

      // 逐个API调用，使用try-catch包装每个调用，确保部分失败不影响整体
      if (exportConfig.dataTypes.includes('sales')) {
        try {
          const result = await fetchWithRetry(() => dashboardAPI.getSalesTrend(parseInt(exportConfig.dateRange) || 30));
          const salesTrend = extractResponseData<SalesTrendItem[]>(result);
          newData.salesTrend = salesTrend || [];
          console.log('成功获取销售趋势数据');
        } catch (error) {
          console.error('获取销售趋势数据失败，使用模拟数据:', error);
          errorMessages.push('销售趋势数据获取失败');
          hasError = true;
          hasApiError = true;
          // 使用模拟数据
          newData.salesTrend = generateMockSalesData(parseInt(exportConfig.dateRange) || 30);
        }
      }
      
      if (exportConfig.dataTypes.includes('categories')) {
        try {
          // 直接使用模拟数据，确保与控制台输出和Dashboard.tsx中的类别销售对比图表保持一致
          newData.categorySales = generateMockCategoryData();
          console.log('使用模拟类别销售数据，与Dashboard.tsx保持一致');
        } catch (error) {
          console.error('生成模拟类别销售数据失败:', error);
          errorMessages.push('类别销售数据生成失败');
          hasError = true;
        }
      }
      
      if (exportConfig.dataTypes.includes('orders')) {
        try {
          latestOrdersFromBackend = latestOrdersFromBackend ?? await fetchOrdersData();
          const ordersSource = latestOrdersFromBackend ?? [];
          if (ordersSource.length === 0) {
            throw new Error('订单数据为空');
          }

          newData.orders = ordersSource.slice(0, 100).map(order => ({
            id: order._id,
            product: order.studentId && typeof order.studentId === 'object' ? order.studentId.shopname || '未知商品' : '未知商品',
            user: order.customerName || '未知用户',
            region: order.address?.split('市')[0] + '市' || '未知地区',
            amount: parsePrice(order.totalPrice) || 0,
            time: order.createdAt ? new Date(order.createdAt).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }) : ''
          }));
        } catch (error) {
          console.error('获取订单明细数据失败，使用模拟数据:', error);
          errorMessages.push('订单明细数据获取失败');
          hasError = true;
          hasApiError = true;
          // 使用模拟数据
          newData.orders = generateMockOrderData(50);
        }
      }
      
      if (exportConfig.dataTypes.includes('comparison')) {
        try {
          const result = await fetchWithRetry(() => dashboardAPI.getComparison());
          const comparison = extractResponseData<DataComparisonItem[]>(result);
          newData.comparison = comparison && comparison.length > 0 ? comparison : undefined;
          // 如果API获取失败或数据为空，使用模拟数据
          if (!newData.comparison || newData.comparison.length === 0) {
            newData.comparison = generateMockComparisonData();
            console.log('使用模拟对比数据，与Dashboard.tsx保持一致');
          }
        } catch (error) {
          console.error('获取数据对比分析失败，使用模拟数据:', error);
          errorMessages.push('数据对比分析获取失败');
          hasError = true;
          // 使用模拟数据
          newData.comparison = generateMockComparisonData();
        }
      }
      
      if (exportConfig.dataTypes.includes('realtime')) {
        try {
          // 与Dashboard.tsx保持一致，从订单和商品数据计算实时数据
          const orders = latestOrdersFromBackend ?? await fetchOrdersData();
          latestOrdersFromBackend = orders;
          await fetchProducts(); // 获取最新商品数据
          
          // 等待商品数据更新
          await new Promise(resolve => setTimeout(resolve, 100));
          
          // 计算实时数据
          const realTimeStats = calculateRealTimeDataFromOrders(orders);
          // 计算总销售额和总订单数，与Dashboard.tsx保持一致
          let totalSales = 0;
          let totalOrders = 0;
          orders.forEach((order: OrderData) => {
            try {
              totalSales += parsePrice(order.totalPrice);
              totalOrders += 1;
            } catch (e) {
              console.warn('[数据导出] 处理订单价格失败:', order._id, e);
            }
          });
          // 获取趋势数据（使用新获取的 comparison 数据，避免依赖 exportData）
          const comparisonData = newData.comparison;
          const salesTrendData = getTrendFromComparison('销售额', comparisonData) || { value: '15.8%', isUp: true };
          const ordersTrendData = getTrendFromComparison('订单数', comparisonData) || { value: '8.2%', isUp: true };
          // 合并实时数据、总统计数据和趋势数据
          newData.realtime = {
            ...realTimeStats,
            totalSales,
            totalOrders,
            users: 12580, // 与Dashboard.tsx保持一致的模拟用户数
            products: productsRef.current.length, // 与Dashboard.tsx保持一致的商品数量计算
            conversionRate: 3.8, // 默认转化率
            stockAlerts: 23, // 默认库存预警数
            returnRate: 2.3, // 默认退货率
            salesTrend: parseFloat(salesTrendData.value),
            ordersTrend: parseFloat(ordersTrendData.value)
          };
          console.log('[数据导出] 成功计算实时数据，包含总销售额和总订单数');
        } catch (error) {
          console.error('计算实时数据失败，使用模拟数据:', error);
          errorMessages.push('实时数据获取失败');
          hasError = true;
          hasApiError = true;
          // 使用模拟数据作为后备，确保包含总销售额和总订单数
          const mockData = createMockRealTimeData(productsRef.current.length);
          newData.realtime = {
            ...mockData,
            totalSales: 131082, // 模拟总销售额
            totalOrders: 7 // 模拟总订单数
          };
        }
      }

      // 更新数据状态
      setExportData(newData);
      
      // 根据错误情况显示不同的提示
      if (hasError) {
        const successCount = Object.keys(newData).length;
        if (successCount > 0) {
          if (hasApiError) {
            alert(`提示: ${errorMessages.join('、')}\n\n已自动使用模拟数据代替，您可以继续导出报表。`);
          } else {
            alert(`部分数据获取失败: ${errorMessages.join('、')}\n\n已成功获取 ${successCount} 项数据，可以继续导出。`);
          }
        } else {
          alert('所有数据获取失败，请重试');
        }
      }
    } catch (error) {
      console.error('获取导出数据时发生未知错误:', error);
      alert('数据处理过程中发生错误，请重试');
    } finally {
      setLoading(false);
    }
  }, [exportConfig.dataTypes, exportConfig.dateRange, fetchOrdersData, fetchProducts, calculateRealTimeDataFromOrders, getTrendFromComparison]);

  // 只在组件挂载或配置变化时获取数据，避免无限循环
  useEffect(() => {
    // 只在有选择的数据类型时才获取数据
    if (exportConfig.dataTypes.length > 0) {
      fetchExportData();
    }
  }, [exportConfig.dataTypes, exportConfig.dateRange, fetchExportData]);

  // 导出PDF
  const exportPDF = async () => {
    if (!previewRef.current) {
      alert('预览内容未准备好，请稍候再试');
      return;
    }
    
    try {
      setLoading(true);
      
      // 等待DOM完全渲染（适当缩短等待时间以减少加载感）
      await new Promise(resolve => setTimeout(resolve, 100));

      // 使用html2canvas捕获预览内容（预览内容已使用内联样式，避免oklch问题）
      const canvas = await html2canvas(previewRef.current, { 
        scale: 2, 
        useCORS: true,
        logging: false,
        backgroundColor: '#ffffff',
        allowTaint: true,
        removeContainer: false,
        windowWidth: 800,
        windowHeight: previewRef.current.scrollHeight
      });
      
      if (!canvas) {
        throw new Error('无法生成画布');
      }
      
      const imgData = canvas.toDataURL('image/png');
      if (!imgData || imgData === 'data:,') {
        throw new Error('无法生成图片数据');
      }
      
      const pdf = new jsPDF('p', 'mm', 'a4');
      const imgWidth = 210;
      const pageHeight = 297;
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      let heightLeft = imgHeight;
      let position = 0;

      pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;

      while (heightLeft > 0) {
        position = heightLeft - imgHeight;
        pdf.addPage();
        pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
      }

      pdf.save(`数据报表_${new Date().toISOString().split('T')[0]}.pdf`);
    } catch (error) {
      console.error('PDF导出失败:', error);
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      alert(`PDF导出失败: ${errorMessage}，请重试`);
    } finally {
      setLoading(false);
    }
  };

  // 导出Word
  const exportWord = async () => {
    try {
      setLoading(true);
      const children: (Paragraph | Table)[] = [];
      
      // 标题
      children.push(new Paragraph({
        text: '数据统计报表',
        heading: 'Heading1',
        alignment: AlignmentType.CENTER
      }));

      // 摘要
      if (exportData.realtime && exportConfig.includeSummary) {
        children.push(new Paragraph({
          children: [
            new TextRun({ text: '数据摘要', bold: true, size: 24 }),
            new TextRun({ text: '\n销售额: ¥' + (exportData.realtime.sales || 0).toLocaleString(), break: 1 }),
            new TextRun({ text: '订单数: ' + (exportData.realtime.orders || 0).toLocaleString(), break: 1 }),
            new TextRun({ text: '用户数: ' + (exportData.realtime.users || 0).toLocaleString(), break: 1 }),
            new TextRun({ text: '总销售额: ¥' + (exportData.realtime.totalSales || 0).toLocaleString(), break: 1 }),
            new TextRun({ text: '总订单数: ' + (exportData.realtime.totalOrders || 0).toLocaleString(), break: 1 })
          ]
        }));
      }

      // 销售数据对比分析
      if (exportData.comparison && exportData.comparison.length > 0) {
        children.push(new Paragraph({
          children: [
            new TextRun({ text: '销售数据对比分析', bold: true, size: 24 })
          ]
        }));

        const comparisonRows = [
          new TableRow({
            children: [
              new TableCell({ children: [new Paragraph('指标')] }),
              new TableCell({ children: [new Paragraph('本期值')] }),
              new TableCell({ children: [new Paragraph('上期值')] }),
              new TableCell({ children: [new Paragraph('环比增长率')] })
            ]
          })
        ];

        exportData.comparison.forEach(item => {
          const currentValue = item.metric === 'sales' ? `¥${(item.currentValue || 0).toLocaleString()}` : `${(item.currentValue || 0).toLocaleString()}${item.unit}`;
          const previousValue = item.metric === 'sales' ? `¥${(item.previousValue || 0).toLocaleString()}` : `${(item.previousValue || 0).toLocaleString()}${item.unit}`;
          comparisonRows.push(new TableRow({
            children: [
              new TableCell({ children: [new Paragraph(item.label)] }),
              new TableCell({ children: [new Paragraph(currentValue)] }),
              new TableCell({ children: [new Paragraph(previousValue)] }),
              new TableCell({ children: [new Paragraph(`${(item.growthRate ?? 0) >= 0 ? '+' : ''}${item.growthRate ?? 0}%`)] })
            ]
          }));
        });

        children.push(new Table({
          rows: comparisonRows,
          width: { size: 100, type: WidthType.PERCENTAGE }
        }));
      }

      // 销售趋势表格
      if (exportData.salesTrend && exportData.salesTrend.length > 0) {
        const rows = [
          new TableRow({
            children: [
              new TableCell({ children: [new Paragraph('日期')] }),
              new TableCell({ children: [new Paragraph('销售额')] }),
              new TableCell({ children: [new Paragraph('订单数')] })
            ]
          })
        ];
        exportData.salesTrend.slice(0, 100).forEach(item => {
          rows.push(new TableRow({
            children: [
              new TableCell({ children: [new Paragraph(item.date)] }),
              new TableCell({ children: [new Paragraph('¥' + (item.sales || 0).toLocaleString())] }),
              new TableCell({ children: [new Paragraph(item.orders.toString())] })
            ]
          }));
        });
        children.push(new Table({
          rows,
          width: { size: 100, type: WidthType.PERCENTAGE }
        }));
      }

      const doc = new Document({ sections: [{ children }] });
      const blob = await Packer.toBlob(doc);
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `数据报表_${new Date().toISOString().split('T')[0]}.docx`;
      link.click();
      URL.revokeObjectURL(url);
    } catch (error) {
      console.error('Word导出失败:', error);
      alert('Word导出失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 导出Excel
  const exportExcel = () => {
    const { salesTrend, categorySales, orders, realtime } = exportData;
    const rows: string[][] = [['数据统计报表'], ['生成时间', new Date().toLocaleString('zh-CN')], []];

    if (realtime && exportConfig.includeSummary) {
      rows.push(['数据摘要'], 
                ['销售额', `¥${(realtime.sales || 0).toLocaleString()}`], 
                ['订单数', (realtime.orders || 0).toLocaleString()],
                ['总销售额', `¥${(realtime.totalSales || 0).toLocaleString()}`],
                ['总订单数', (realtime.totalOrders || 0).toLocaleString()], 
                []);
    }

    if (exportData.comparison && exportData.comparison.length > 0) {
      rows.push(['销售数据对比分析'], ['指标', '本期值', '上期值', '环比增长率']);
      exportData.comparison.forEach(item => {
          const currentValue = item.metric === 'sales' ? `¥${(item.currentValue || 0).toLocaleString()}` : `${(item.currentValue || 0).toLocaleString()}${item.unit}`;
          const previousValue = item.metric === 'sales' ? `¥${(item.previousValue || 0).toLocaleString()}` : `${(item.previousValue || 0).toLocaleString()}${item.unit}`;
        rows.push([item.label, currentValue, previousValue, `${(item.growthRate ?? 0) >= 0 ? '+' : ''}${item.growthRate ?? 0}%`]);
      });
      rows.push([]);
    }

    if (salesTrend && salesTrend.length > 0) {
      rows.push(['销售趋势数据'], ['日期', '销售额(元)', '订单数']);
      salesTrend.forEach(item => rows.push([item.date, item.sales.toString(), item.orders.toString()]));
      rows.push([]);
    }

    if (categorySales && categorySales.length > 0) {
      rows.push(['类别销售数据'], ['类别名称', '销售额(元)', '订单数']);
      categorySales.forEach(item => rows.push([item.name, item.sales.toString(), item.orders.toString()]));
      rows.push([]);
    }

    if (orders && orders.length > 0) {
      const activeColumns = orderColumns.length > 0 ? orderColumns : ['product'];
      const headerRow = activeColumns.map(col => {
        const option = orderColumnOptions.find(o => o.id === col);
        return option ? option.label : col;
      });
      rows.push(['订单明细']);
      rows.push(headerRow);
      orders.forEach(order => {
        const dataRow = activeColumns.map(col => {
          switch (col) {
            case 'product':
              return order.product;
            case 'user':
              return order.user;
            case 'region':
              return order.region;
            case 'amount':
              return order.amount.toString();
            case 'time':
              return order.time;
            default:
              return '';
          }
        });
        rows.push(dataRow);
      });
    }

    const csvContent = rows.map(row => row.map(cell => `"${cell}"`).join(',')).join('\n');
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `数据报表_${new Date().toISOString().split('T')[0]}.xlsx`;
    link.click();
  };

  // 导出图片
  const exportImage = async () => {
    if (!previewRef.current) {
      alert('预览内容未准备好，请稍候再试');
      return;
    }
    
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 100));
      
      const canvas = await html2canvas(previewRef.current, { 
        scale: 2, 
        useCORS: true,
        logging: false,
        backgroundColor: '#ffffff',
        allowTaint: true,
        windowWidth: 800,
        windowHeight: previewRef.current.scrollHeight
      });
      
      if (!canvas) {
        throw new Error('无法生成画布');
      }
      
      canvas.toBlob((blob) => {
        if (blob) {
          const url = URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = `数据报表_${new Date().toISOString().split('T')[0]}.png`;
          link.click();
          URL.revokeObjectURL(url);
        } else {
          throw new Error('无法生成图片数据');
        }
      }, 'image/png');
    } catch (error) {
      console.error('图片导出失败:', error);
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      alert(`图片导出失败: ${errorMessage}，请重试`);
    } finally {
      setLoading(false);
    }
  };

  // 实际执行导出
  const performExport = async () => {
    if (exportConfig.dataTypes.length === 0) {
      alert('请至少选择一种数据类型');
      return;
    }

    try {
      // 确保导出前数据是最新的
      await fetchExportData();

      switch (exportConfig.format) {
        case 'pdf':
          await exportPDF();
          break;
        case 'word':
          await exportWord();
          break;
        case 'excel':
          exportExcel();
          break;
        case 'image':
          await exportImage();
          break;
      }
      const typesText = exportConfig.dataTypes
        .map(type => dataTypeOptions.find(opt => opt.id === type)?.label || type)
        .join('、');
      const successItem: ExportHistoryItem = {
        id: `${Date.now()}`,
        time: new Date().toLocaleString('zh-CN'),
        types: typesText,
        format: exportConfig.format.toUpperCase(),
        status: '成功',
        config: {
          dataTypes: [...exportConfig.dataTypes],
          dateRange: exportConfig.dateRange,
          format: exportConfig.format,
          orderColumns: [...orderColumns],
        },
      };
      setExportHistory(prev => [successItem, ...prev].slice(0, 50));
    } catch (error) {
      console.error('导出失败:', error);
      const errorMessage = error instanceof Error && error.message
        ? error.message
        : '未知错误，请检查网络或稍后再试';
      alert(`导出失败: ${errorMessage}`);
      const typesText = exportConfig.dataTypes
        .map(type => dataTypeOptions.find(opt => opt.id === type)?.label || type)
        .join('、');
      const failItem: ExportHistoryItem = {
        id: `${Date.now()}`,
        time: new Date().toLocaleString('zh-CN'),
        types: typesText,
        format: exportConfig.format.toUpperCase(),
        status: '失败',
        message: '导出失败',
        config: {
          dataTypes: [...exportConfig.dataTypes],
          dateRange: exportConfig.dateRange,
          format: exportConfig.format,
          orderColumns: [...orderColumns],
        },
      };
      setExportHistory(prev => [failItem, ...prev].slice(0, 50));
    }
  };

  // 点击“导出报表”时先弹出确认框
  const handleExport = () => {
    if (exportConfig.dataTypes.length === 0) {
      alert('请至少选择一种数据类型');
      return;
    }
    setConfirmVisible(true);
  };

  const getExportStats = () => {
    let totalRecords = 0;
    if (exportConfig.dataTypes.includes('sales') && exportData.salesTrend) {
      totalRecords += exportData.salesTrend.length;
    }
    if (exportConfig.dataTypes.includes('categories') && exportData.categorySales) {
      totalRecords += exportData.categorySales.length;
    }
    if (exportConfig.dataTypes.includes('orders') && exportData.orders) {
      totalRecords += exportData.orders.length;
    }
    if (exportConfig.dataTypes.includes('comparison') && exportData.comparison) {
      totalRecords += exportData.comparison.length;
    }

    const averageBytesPerRecord = 200;
    const totalBytes = totalRecords * averageBytesPerRecord;
    let sizeText = '约 0 KB';
    if (totalBytes > 0) {
      if (totalBytes < 1024 * 1024) {
        sizeText = `约 ${(totalBytes / 1024).toFixed(1)} KB`;
      } else {
        sizeText = `约 ${(totalBytes / (1024 * 1024)).toFixed(1)} MB`;
      }
    }

    return { totalRecords, sizeText };
  };

  // 生成预览内容
  const renderPreview = () => (
    <div style={{ backgroundColor: '#ffffff', padding: '32px', minWidth: '800px' }}>
      <h1 style={{ fontSize: '30px', fontWeight: 'bold', color: '#2563eb', marginBottom: '8px', borderBottom: '4px solid #3b82f6', paddingBottom: '8px' }}>数据统计报表</h1>
      <p style={{ color: '#4b5563', marginBottom: '24px' }}>生成时间: {new Date().toLocaleString('zh-CN')} | 统计周期: 最近{exportConfig.dateRange}天</p>
      
      {exportData.realtime && exportConfig.includeSummary && (
        <div style={{ backgroundColor: '#eff6ff', padding: '24px', borderRadius: '8px', marginBottom: '24px' }}>
          <h2 style={{ fontSize: '20px', fontWeight: 'bold', color: '#1e40af', marginBottom: '16px' }}>数据摘要</h2>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '16px' }}>
            <div style={{ backgroundColor: '#ffffff', padding: '16px', borderRadius: '8px', boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#2563eb' }}>¥{exportData.realtime.sales.toLocaleString()}</div>
              <div style={{ fontSize: '14px', color: '#4b5563', marginTop: '4px' }}>销售额</div>
            </div>
            <div style={{ backgroundColor: '#ffffff', padding: '16px', borderRadius: '8px', boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#16a34a' }}>{exportData.realtime.orders.toLocaleString()}</div>
              <div style={{ fontSize: '14px', color: '#4b5563', marginTop: '4px' }}>订单数</div>
            </div>
            <div style={{ backgroundColor: '#ffffff', padding: '16px', borderRadius: '8px', boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#9333ea' }}>{exportData.realtime.users?.toLocaleString() || 12580}</div>
              <div style={{ fontSize: '14px', color: '#4b5563', marginTop: '4px' }}>用户数</div>
            </div>
            <div style={{ backgroundColor: '#ffffff', padding: '16px', borderRadius: '8px', boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#ea580c' }}>{exportData.realtime.products?.toLocaleString() || 568}</div>
              <div style={{ fontSize: '14px', color: '#4b5563', marginTop: '4px' }}>商品数</div>
            </div>
          </div>
        </div>
      )}

      {exportData.salesTrend && exportData.salesTrend.length > 0 && (
        <div style={{ marginBottom: '24px' }}>
          <h2 style={{ fontSize: '20px', fontWeight: 'bold', color: '#1f2937', marginBottom: '16px', borderLeft: '4px solid #3b82f6', paddingLeft: '12px' }}>销售趋势数据</h2>
          <table style={{ width: '100%', borderCollapse: 'collapse', border: '1px solid #d1d5db' }}>
            <thead>
              <tr style={{ backgroundColor: '#3b82f6', color: '#ffffff' }}>
                <th style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'left' }}>日期</th>
                <th style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'right' }}>销售额(元)</th>
                <th style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'right' }}>订单数</th>
                <th style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'right' }}>客单价(元)</th>
              </tr>
            </thead>
            <tbody>
              {exportData.salesTrend.slice(0, 50).map((item, idx) => (
                <tr key={idx} style={{ backgroundColor: idx % 2 === 0 ? '#f9fafb' : '#ffffff' }}>
                  <td style={{ border: '1px solid #d1d5db', padding: '12px' }}>{item.date}</td>
                  <td style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'right' }}>¥{(item.sales || 0).toLocaleString()}</td>
              <td style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'right' }}>{(item.orders || 0).toLocaleString()}</td>
                  <td style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'right' }}>¥{(item.orders > 0 ? item.sales / item.orders : 0).toFixed(2)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {exportData.categorySales && exportData.categorySales.length > 0 && (
        <div style={{ marginBottom: '24px' }}>
          <h2 style={{ fontSize: '20px', fontWeight: 'bold', color: '#1f2937', marginBottom: '16px', borderLeft: '4px solid #22c55e', paddingLeft: '12px' }}>类别销售数据</h2>
          <table style={{ width: '100%', borderCollapse: 'collapse', border: '1px solid #d1d5db' }}>
            <thead>
              <tr style={{ backgroundColor: '#22c55e', color: '#ffffff' }}>
                <th style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'left' }}>类别名称</th>
                <th style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'right' }}>销售额(元)</th>
                <th style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'right' }}>订单数</th>
                <th style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'right' }}>占比</th>
              </tr>
            </thead>
            <tbody>
              {exportData.categorySales.map((item, idx) => {
                const total = exportData.categorySales!.reduce((sum, i) => sum + i.sales, 0);
                const percentage = total > 0 ? ((item.sales / total) * 100).toFixed(2) : '0.00';
                return (
                  <tr key={idx} style={{ backgroundColor: idx % 2 === 0 ? '#f9fafb' : '#ffffff' }}>
                    <td style={{ border: '1px solid #d1d5db', padding: '12px' }}>{item.name}</td>
                    <td style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'right' }}>¥{item.sales.toLocaleString()}</td>
                    <td style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'right' }}>{item.orders.toLocaleString()}</td>
                    <td style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: 'right' }}>{percentage}%</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {exportData.comparison && exportData.comparison.length > 0 && (
        <div style={{ marginBottom: '24px' }}>
          <h2 style={{ fontSize: '20px', fontWeight: 'bold', color: '#1f2937', marginBottom: '16px', borderLeft: '4px solid #f59e0b', paddingLeft: '12px' }}>销售数据对比分析</h2>
          <div style={{ backgroundColor: '#ffffff', padding: '24px', borderRadius: '8px', boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
            {exportData.comparison.map((item, idx) => (
              <div key={idx} style={{ marginBottom: idx < (exportData.comparison?.length ?? 0) - 1 ? '24px' : '0' }}>
                <div style={{ fontSize: '16px', fontWeight: '500', color: '#4b5563', marginBottom: '12px' }}>{item.label} vs {item.previousLabel}</div>
                <div style={{ display: 'flex', alignItems: 'end', gap: '16px', marginBottom: '8px' }}>
                  <div>
                    <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#2563eb' }}>
                      {item.metric === 'sales' ? '¥' : ''}{(item.currentValue || 0).toLocaleString()}{item.unit}
                    </div>
                    <div style={{ fontSize: '14px', color: '#6b7280', marginTop: '4px' }}>{item.label}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#9ca3af' }}>
                      {item.metric === 'sales' ? '¥' : ''}{(item.previousValue || 0).toLocaleString()}{item.unit}
                    </div>
                    <div style={{ fontSize: '14px', color: '#6b7280', marginTop: '4px' }}>{item.previousLabel}</div>
                  </div>
                  <div style={{ fontSize: '18px', fontWeight: 'bold', color: (item.growthRate ?? 0) >= 0 ? '#16a34a' : '#dc2626', marginLeft: 'auto' }}>
                    {(item.growthRate ?? 0) >= 0 ? '+' : ''}{item.growthRate ?? 0}% <span style={{ fontSize: '14px', fontWeight: 'normal' }}>(环比)</span>
                  </div>
                </div>
                <div style={{ position: 'relative', height: '24px', backgroundColor: '#f3f4f6', borderRadius: '4px', overflow: 'hidden' }}>
                  <div 
                    style={{ 
                      position: 'absolute', 
                      left: '0', 
                      bottom: '0', 
                      height: '100%', 
                      backgroundColor: '#9ca3af', 
                      width: `${Math.min(100, (item.previousValue / Math.max(item.currentValue, item.previousValue)) * 100)}%`,
                      transition: 'width 0.3s ease'
                    }}
                  />
                  <div 
                    style={{ 
                      position: 'absolute', 
                      left: '0', 
                      bottom: '0', 
                      height: '100%', 
                      backgroundColor: '#3b82f6', 
                      width: `${Math.min(100, (item.currentValue / Math.max(item.currentValue, item.previousValue)) * 100)}%`,
                      transition: 'width 0.3s ease'
                    }}
                  />
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {exportData.orders && exportData.orders.length > 0 && (
        <div style={{ marginBottom: '24px' }}>
          <h2 style={{ fontSize: '20px', fontWeight: 'bold', color: '#1f2937', marginBottom: '16px', borderLeft: '4px solid #a855f7', paddingLeft: '12px' }}>订单明细</h2>
          <table style={{ width: '100%', borderCollapse: 'collapse', border: '1px solid #d1d5db' }}>
            <thead>
              <tr style={{ backgroundColor: '#a855f7', color: '#ffffff' }}>
                { (orderColumns.length > 0 ? orderColumns : ['product']).map(col => {
                  const option = orderColumnOptions.find(o => o.id === col);
                  const label = option ? option.label : col;
                  const align = col === 'amount' ? 'right' : 'left';
                  return (
                    <th
                      key={col}
                      style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: align as 'left' | 'right' }}
                    >
                      {label}
                    </th>
                  );
                })}
              </tr>
            </thead>
            <tbody>
              {exportData.orders.slice(0, 50).map((order, idx) => (
                <tr key={idx} style={{ backgroundColor: idx % 2 === 0 ? '#f9fafb' : '#ffffff' }}>
                  {(orderColumns.length > 0 ? orderColumns : ['product']).map(col => {
                    let value: string = '';
                    let align: 'left' | 'right' = 'left';
                    switch (col) {
                      case 'product':
                        value = order.product;
                        align = 'left';
                        break;
                      case 'user':
                        value = order.user;
                        align = 'left';
                        break;
                      case 'region':
                        value = order.region;
                        align = 'left';
                        break;
                      case 'amount':
                        value = `¥${(order.amount || 0).toLocaleString()}`;
                        align = 'right';
                        break;
                      case 'time':
                        value = order.time;
                        align = 'left';
                        break;
                      default:
                        value = '';
                        align = 'left';
                    }
                    return (
                      <td
                        key={col}
                        style={{ border: '1px solid #d1d5db', padding: '12px', textAlign: align }}
                      >
                        {value}
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
    <div>
        <h2 className="text-2xl font-bold text-gray-800">数据导出</h2>
          <p className="text-gray-500 mt-1">导出各类数据报表（PDF/Word/Excel/图片）</p>
        </div>
        <div className="flex items-center gap-3">
          <button onClick={() => setPreviewVisible(true)} className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
            <Eye size={18} /> 预览报表
          </button>
          <button
            onClick={fetchExportData}
            disabled={loading}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
              loading
                ? 'bg-gray-400 text-white cursor-not-allowed'
                : 'bg-gray-500 text-white hover:bg-gray-600'
            }`}
          >
            <RefreshCw size={18} /> {loading ? '刷新中...' : '刷新数据'}
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-6">
          <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
            <div className="flex items-center gap-2 mb-4">
              <CheckSquare size={20} className="text-blue-600" />
              <h3 className="text-lg font-bold text-gray-800">选择数据类型</h3>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {dataTypeOptions.map(option => (
                <div key={option.id} onClick={() => {
                  setExportConfig(prev => ({
                    ...prev,
                    dataTypes: prev.dataTypes.includes(option.id)
                      ? prev.dataTypes.filter(t => t !== option.id)
                      : [...prev.dataTypes, option.id]
                  }));
                }} className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                  exportConfig.dataTypes.includes(option.id) ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300'
                }`}>
                  <div className="flex items-center gap-3">
                    {exportConfig.dataTypes.includes(option.id) ? <CheckSquare size={20} className="text-blue-600" /> : <Square size={20} className="text-gray-400" />}
                    <div className="flex-1">
                      <div className="font-semibold text-gray-800">{option.label}</div>
                      <div className="text-xs text-gray-500 mt-1">{option.description}</div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
            <div className="flex items-center gap-2 mb-4">
              <Settings size={20} className="text-blue-600" />
              <h3 className="text-lg font-bold text-gray-800">导出选项</h3>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">导出模板</label>
                <div className="flex flex-wrap gap-2">
                  {exportPresets.map(preset => {
                    const isActive =
                      preset.config.format === exportConfig.format &&
                      preset.config.dateRange === exportConfig.dateRange &&
                      preset.config.dataTypes.length === exportConfig.dataTypes.length &&
                      preset.config.dataTypes.every(t => exportConfig.dataTypes.includes(t));
                    return (
                      <button
                        key={preset.id}
                        type="button"
                        onClick={() => {
                          setExportConfig(prev => ({
                            ...prev,
                            dataTypes: preset.config.dataTypes,
                            dateRange: preset.config.dateRange,
                            format: preset.config.format
                          }));
                        }}
                        className={`px-3 py-1.5 rounded-full text-xs border transition-colors ${
                          isActive
                            ? 'bg-blue-50 text-blue-700 border-blue-400'
                            : 'bg-gray-50 text-gray-600 border-gray-300 hover:border-gray-400'
                        }`}
                        title={preset.description}
                      >
                        {preset.name}
                      </button>
                    );
                  })}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">统计周期</label>
                <div className="flex flex-col gap-2">
                  <div className="flex items-center gap-2">
                    {['7', '30', '90'].map((days) => (
                      <button
                        key={days}
                        type="button"
                        onClick={() => setExportConfig(prev => ({ ...prev, dateRange: days }))}
                        className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                          exportConfig.dateRange === days
                            ? 'bg-blue-500 text-white'
                            : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                        }`}
                      >
                        最近{days}天
                      </button>
                    ))}
                  </div>
                  <div className="flex flex-wrap gap-2 text-xs text-gray-600">
                    {[
                      { id: 'this-week', label: '本周', days: '7' },
                      { id: 'this-month', label: '本月', days: '30' },
                      { id: 'last-month', label: '上月', days: '30' },
                      { id: 'this-quarter', label: '本季度', days: '90' }
                    ].map(option => (
                      <button
                        key={option.id}
                        type="button"
                        onClick={() => setExportConfig(prev => ({ ...prev, dateRange: option.days }))}
                        className={`px-3 py-1 rounded-full border transition-colors ${
                          exportConfig.dateRange === option.days
                            ? 'bg-blue-50 text-blue-700 border-blue-400'
                            : 'bg-gray-50 text-gray-600 border-gray-300 hover:border-gray-400'
                        }`}
                      >
                        {option.label}
                      </button>
                    ))}
                  </div>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">导出格式</label>
                <div className="grid grid-cols-4 gap-3">
                  {[
                    { id: 'pdf', label: 'PDF', icon: FileText, color: 'bg-red-500' },
                    { id: 'word', label: 'Word', icon: File, color: 'bg-indigo-500' },
                    { id: 'excel', label: 'Excel', icon: FileSpreadsheet, color: 'bg-green-500' },
                    { id: 'image', label: '图片', icon: Image, color: 'bg-purple-500' }
                  ].map(format => {
                    const Icon = format.icon;
                    return (
                      <button key={format.id} onClick={() => setExportConfig(prev => ({ ...prev, format: format.id as 'pdf' | 'excel' | 'word' | 'image' }))}
                        className={`p-4 rounded-lg border-2 transition-all ${
                          exportConfig.format === format.id ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300'
                        }`}>
                        <div className={`${format.color} w-12 h-12 rounded-lg flex items-center justify-center mb-2 mx-auto`}>
                          <Icon size={24} className="text-white" />
                        </div>
                        <div className="text-sm font-medium text-gray-800">{format.label}</div>
                      </button>
                    );
                  })}
                </div>
              </div>

              <div className="space-y-3">
                <label className="flex items-center gap-3 cursor-pointer">
                  <input type="checkbox" checked={exportConfig.includeSummary} onChange={(e) => setExportConfig(prev => ({ ...prev, includeSummary: e.target.checked }))} className="w-5 h-5 text-blue-600 rounded" />
                  <span className="text-sm text-gray-700">包含数据摘要</span>
                </label>
                <label className="flex items-center gap-3 cursor-pointer">
                  <input type="checkbox" checked={exportConfig.includeCharts} onChange={(e) => setExportConfig(prev => ({ ...prev, includeCharts: e.target.checked }))} className="w-5 h-5 text-blue-600 rounded" />
                  <span className="text-sm text-gray-700">包含图表说明</span>
                </label>
              </div>

              {exportConfig.dataTypes.includes('orders') && (
                <div className="space-y-2 pt-2 border-t border-gray-100">
                  <label className="block text-sm font-medium text-gray-700">订单字段</label>
                  <div className="flex flex-wrap gap-2">
                    {orderColumnOptions.map(option => {
                      const active = orderColumns.includes(option.id);
                      return (
                        <button
                          key={option.id}
                          type="button"
                          onClick={() => {
                            setOrderColumns(prev => {
                              if (prev.includes(option.id)) {
                                if (prev.length === 1) return prev;
                                return prev.filter(c => c !== option.id);
                              }
                              return [...prev, option.id];
                            });
                          }}
                          className={`px-3 py-1.5 rounded-full text-xs border transition-colors ${
                            active
                              ? 'bg-blue-50 text-blue-700 border-blue-400'
                              : 'bg-gray-50 text-gray-600 border-gray-300 hover:border-gray-400'
                          }`}
                        >
                          {option.label}
                        </button>
                      );
                    })}
                  </div>
                  <p className="text-xs text-gray-400">至少保留一列，导出时仅包含选中的订单字段。</p>
                </div>
              )}
            </div>
          </div>
        </div>

        <div className="space-y-6">
          <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
            <h3 className="text-lg font-bold text-gray-800 mb-4">数据预览</h3>
            <div className="space-y-3">
              {exportConfig.dataTypes.includes('sales') && exportData.salesTrend && (
                <div className="p-3 bg-blue-50 rounded-lg">
                  <div className="text-sm font-medium text-blue-900">销售趋势</div>
                  <div className="text-xs text-blue-700 mt-1">{exportData.salesTrend.length} 条记录</div>
                </div>
              )}
              {exportConfig.dataTypes.includes('categories') && exportData.categorySales && (
                <div className="p-3 bg-green-50 rounded-lg">
                  <div className="text-sm font-medium text-green-900">类别销售</div>
                  <div className="text-xs text-green-700 mt-1">{exportData.categorySales.length} 个类别</div>
                </div>
              )}
              {exportConfig.dataTypes.includes('orders') && exportData.orders && (
                <div className="p-3 bg-purple-50 rounded-lg">
                  <div className="text-sm font-medium text-purple-900">订单明细</div>
                  <div className="text-xs text-purple-700 mt-1">{exportData.orders.length} 条订单</div>
                </div>
              )}
              {exportConfig.dataTypes.includes('comparison') && exportData.comparison && (
                <div className="p-3 bg-amber-50 rounded-lg">
                  <div className="text-sm font-medium text-amber-900">销售数据对比</div>
                  <div className="text-xs text-amber-700 mt-1">{exportData.comparison.length} 项指标</div>
                </div>
              )}
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
            <h3 className="text-lg font-bold text-gray-800 mb-4">生成报表</h3>
            {(() => {
              const stats = getExportStats();
              if (!stats.totalRecords) return null;
              return (
                <div className="mb-3 text-xs text-gray-500">
                  预计导出<span className="font-semibold text-gray-800"> {stats.totalRecords} </span>条记录，文件大小<span className="font-semibold text-gray-800"> {stats.sizeText}</span>。
                </div>
              );
            })()}
            <button
              onClick={handleExport}
              disabled={exportConfig.dataTypes.length === 0}
              className={`w-full flex items-center justify-center gap-2 px-6 py-3 bg-gradient-to-r from-blue-500 to-indigo-600 text-white rounded-lg transition-all hover:from-blue-600 hover:to-indigo-700 ${
                exportConfig.dataTypes.length === 0 ? 'opacity-50 cursor-not-allowed' : ''
              }`}
            >
              <Download size={20} /> 导出报表 ({exportConfig.format.toUpperCase()})
            </button>
            <p className="mt-2 text-xs text-gray-500">
              将导出：
              {exportConfig.dataTypes
                .map(type => dataTypeOptions.find(opt => opt.id === type)?.label || type)
                .join('、')}
              ，格式：{exportConfig.format.toUpperCase()}。
            </p>
            {exportConfig.dataTypes.length === 0 && (
              <p className="mt-2 text-sm text-red-500">请至少选择一种数据类型，才能导出报表。</p>
            )}
          </div>
        </div>
      </div>

      <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
        <h3 className="text-lg font-bold text-gray-800 mb-4">导出历史</h3>
        {exportHistory.length === 0 ? (
          <p className="text-sm text-gray-500">暂无导出记录。</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="min-w-full text-sm">
              <thead>
                <tr className="bg-gray-50 text-gray-600">
                  <th className="px-3 py-2 text-left font-medium">时间</th>
                  <th className="px-3 py-2 text-left font-medium">数据类型</th>
                  <th className="px-3 py-2 text-left font-medium">格式</th>
                  <th className="px-3 py-2 text-left font-medium">状态</th>
                  <th className="px-3 py-2 text-left font-medium">备注</th>
                  <th className="px-3 py-2 text-left font-medium">操作</th>
                </tr>
              </thead>
              <tbody>
                {exportHistory.map(item => (
                  <tr key={item.id} className="border-t border-gray-100">
                    <td className="px-3 py-2 text-gray-700 whitespace-nowrap">{item.time}</td>
                    <td className="px-3 py-2 text-gray-700">{item.types}</td>
                    <td className="px-3 py-2 text-gray-700">{item.format}</td>
                    <td className="px-3 py-2">
                      <span
                        className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                          item.status === '成功'
                            ? 'bg-green-50 text-green-700'
                            : 'bg-red-50 text-red-700'
                        }`}
                      >
                        {item.status}
                      </span>
                    </td>
                    <td className="px-3 py-2 text-gray-500 text-xs">{item.message || '--'}</td>
                    <td className="px-3 py-2">
                      <button
                        type="button"
                        className="px-3 py-1 rounded-full border border-blue-400 text-xs text-blue-700 hover:bg-blue-50 disabled:opacity-60"
                        onClick={() => {
                          setExportConfig(prev => ({
                            ...prev,
                            dataTypes: item.config.dataTypes,
                            dateRange: item.config.dateRange,
                            format: item.config.format,
                          }));
                          setOrderColumns(
                            item.config.orderColumns && item.config.orderColumns.length > 0
                              ? item.config.orderColumns
                              : ['product', 'user', 'region', 'amount', 'time']
                          );
                          setConfirmVisible(true);
                        }}
                      >
                        再次导出
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* 预览弹窗 */}
      {previewVisible && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4" onClick={() => setPreviewVisible(false)}>
          <div className="bg-white rounded-2xl shadow-2xl max-w-6xl max-h-[90vh] overflow-auto" onClick={(e) => e.stopPropagation()}>
            <div className="sticky top-0 bg-white border-b p-4 flex items-center justify-between">
              <h3 className="text-xl font-bold">报表预览</h3>
              <button onClick={() => setPreviewVisible(false)} className="text-gray-600 hover:text-gray-800">✕</button>
            </div>
            <div className="p-4">{renderPreview()}</div>
          </div>
        </div>
      )}

      {/* 导出确认弹窗 */}
      {confirmVisible && (
        <div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 p-4" onClick={() => setConfirmVisible(false)}>
          <div
            className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6 space-y-4"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-bold text-gray-800">确认导出报表</h3>
              <button
                type="button"
                className="text-gray-400 hover:text-gray-600"
                onClick={() => setConfirmVisible(false)}
              >
                ✕
              </button>
            </div>
            <div className="text-sm text-gray-600 space-y-1">
              <p>将按当前配置导出报表：</p>
              <p>
                数据类型：
                {exportConfig.dataTypes
                  .map((type) => dataTypeOptions.find((opt) => opt.id === type)?.label || type)
                  .join('、')}
              </p>
              <p>导出格式：{exportConfig.format.toUpperCase()}</p>
              {(() => {
                const stats = getExportStats();
                if (!stats.totalRecords) return null;
                return (
                  <p>
                    预计导出 <span className="font-semibold text-gray-800">{stats.totalRecords}</span> 条记录，
                    文件大小约 <span className="font-semibold text-gray-800">{stats.sizeText}</span>。
                  </p>
                );
              })()}
            </div>
            <div className="flex justify-end gap-3 pt-2">
              <button
                type="button"
                className="px-4 py-2 rounded-lg border border-gray-300 text-sm text-gray-700 hover:bg-gray-50"
                onClick={() => setConfirmVisible(false)}
              >
                取消
              </button>
              <button
                type="button"
                className="px-4 py-2 rounded-lg bg-gradient-to-r from-blue-500 to-indigo-600 text-sm text-white hover:from-blue-600 hover:to-indigo-700 flex items-center gap-2"
                onClick={() => {
                  setConfirmVisible(false);
                  performExport();
                }}
              >
                确认导出
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 隐藏的预览内容（用于导出） */}
      <div 
        ref={previewRef}
        className="fixed -left-[9999px] top-0 bg-white"
        style={{ width: '800px', minHeight: '100px' }}
      >
        {renderPreview()}
      </div>
    </div>
  )
}

export default DataExport
